import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;


class AddInventory {

	JLabel l1,l2,l3,l4;
	JTextField t1,t2,t3,t4;
	JButton jb1,jb2;
	JPanel jp1,jp2;

public void addInventory()
	{
	JFrame jf=new JFrame("Addition of a New Inventory Item");
	jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	jf.setBackground(Color.white);
	jf.setSize(400,300);
	jf.setLocation(250,200);
        jf.setVisible(true);
	jf.setLayout(new BorderLayout(30,30));
	JLabel jl=new JLabel("Enter the following details of the inventory item");
	jp1=new JPanel();
	jp1.setLayout(new GridLayout(1,1));
	jp1.add(jl);
	jf.add(jp1,BorderLayout.NORTH);
	jp2=new JPanel();
	jp2.setLayout(new GridLayout(6,2,10,10));

	l1=new JLabel("Name of the Item:");
	jp2.add(l1);
	t1=new JTextField();
	jp2.add(t1);
	l2=new JLabel("Unique ID of the Item:");
	jp2.add(l2);
	t2=new JTextField();
	jp2.add(t2);
	l3=new JLabel("Quantity of the Item:");
	jp2.add(l3);
	t3=new JTextField();
	jp2.add(t3);
	l4=new JLabel("Price of the Item:");
	jp2.add(l4);
	t4=new JTextField();
	jp2.add(t4);
	jb1=new JButton("Add");
	jp2.add(jb1);
	jb2=new JButton("Clear");
	jp2.add(jb2);
	jf.add(jp2,BorderLayout.CENTER);

	jb1.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent e)
	{
	savetoFile();
	clear();
	}

	});


	jb2.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent e)
	{
	clear();
	}});

	}

	public void clear()
	{
	t1.setText("");
	t2.setText("");
	t3.setText("");
	t4.setText("");
	return;
	}

	public void savetoFile()
	{

	 InventoryList a = new InventoryList();
         Vector v = a.getInventories();
         Inventory q = new Inventory();
	Inventory p = new Inventory();
	InventoryList obj=new InventoryList();

	if(new File("inventory.xml").exists())
	    {
	 	try {

               XMLDecoder istream = new XMLDecoder(new BufferedInputStream(new FileInputStream("inventory.xml")));
               obj =(InventoryList) istream.readObject();
                istream.close();
		}

		catch(Exception ex) {
         	System.out.println(ex);
      		}
	     }

	for(int i=0;i<obj.inventories.size();i++)
	{
	p=(Inventory) obj.inventories.get(i);
	v.add(p);
	}


        q.setName(t1.getText());
	q.setInventoryid(Integer.parseInt(t2.getText()));
	q.setQuantity(Integer.parseInt(t3.getText()));
	q.setPrice(Integer.parseInt(t4.getText()));

         v.add(q);

	try {
	XMLEncoder xe = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("inventory.xml")));

            xe.writeObject(a);
	    //xe.flush();
            xe.close();
	JOptionPane.showMessageDialog(null,"Inventory is added successfully");
         }
      catch(Exception ex) {
         System.out.println(ex);
      }
	}
}
